;(function (window, doc, $) {
	//base on jQuery、jQuery-form、BootStrap
	var from = function(){
		var o = arguments[0];
		if(o && $.isFunction(o.toLowerCase))
			o = o.toLowerCase();
		for(var i=2; i<arguments.length; i++)
			if(arguments[i][0] == o)
				return arguments[i][1];
		return arguments[1]; 
	};
    var ON_STATUS = {
        FOLDER_SELECT: "ms-hover",
        IMG_SELECT: "img-selected"
    };
    var DATA_TYPE = {
        JSON: "json",
        COMMA_SPLIT: "comma-split",
        from: function(t){return from(t, this.COMMA_SPLIT, ['json', this.JSON])}
    };
    var MODE = {
        SINGLE: 0,
        MULTI: 1,
        from: function(t){return from(t, this.SINGLE, ['multi', this.MULTI])}
    };
    var LOAD_STATUS = {
        NOT_START: 0,
        LOADING: 1,
        LOAD_PARTITION: 2,
        LOAD_FINISH: 3
    };
    var IU_STATUS = {
        SELECT: 0,
        DELETE: 1
    };
    var AJAX_ERR = {
        "empty_folder": "文件名不能为空",
        "invalid_folder_name": "文件夹名包含不可用字符： .. / \\等",
        "folder_name_too_long": "文件夹名字过长。"
    };
    var iu = {
        curFolder: null,
        curImgSlt: null,
        curSelectImages: [],

        status: IU_STATUS.SELECT,

        pageSize: 20,
        urls: {
            uploadImage: 'upload_image.do',
            listImage: 'list_image.do',
            deleteImage: 'delete_image.do',
            listFolder: 'upload_image_folder_list.do',
            deleteFolder: 'upload_image_folder_delete.do',
            createFolder: 'create_folder.do'
        },
        inited: false,
        folders: [],
        imageSelects: [],
        dom: {},

        initSelect: function(initEle, uOpt){
            this.init();
            var isArr = this.imageSelects;
            var isInx = -1;
            var is = isArr.find(function(e, i){
                isInx = i;
                return e.initEle[0] == initEle[0];
            });
            if(is){
                is.remove();
                isArr.splice(isInx, 1);
            }
            var is = new ImageSelect(initEle, this, uOpt);
            isArr.push(is);
            return is;
        },
        userStart: function(is){
            var lastCurImgSlt = this.curImgSlt;
            this.curImgSlt = is;
            if(lastCurImgSlt != this.curImgSlt){
                this.clearSelectResult();
            }
            this.dom.modal.modal({
                keyboard: false,
                backdrop: false
            });
            this.statusRefresh();
        },
        clearSelectResult: function(){
            $.each(this.curSelectImages, function (i, e) {
                e.select(false);
                e.folder.imgSelect(e);
            });
            this.curSelectImages.splice(0, this.curSelectImages.length);
        },
        loadFolder: function(defaultSltFolder){
            var that = this;
            $.getJSON(that.urls.listFolder, function(data){
                var folderData = [];
                if(data.state == 'SUCCESS' && data.folders)
                    folderData = data.folders;
                
                var oldData = that.folders;
                var newFolderArr = [];
                that.dom.body.folderItemPanel.empty();
                $.each(folderData, function(i, e){
                    var o = oldData.find(function(of){ return e.name == of.name;});
                    if(!o){
                        o = new Folder(e, that);
                    } else {
                    	o.empty = e.empty;
                    }
                    o.appendToPanel();
                    newFolderArr.push(o);
                });
                
                if(defaultSltFolder){
                    if(that.curFolder)
                        that.curFolder.select(false);
                    that.curFolder = newFolderArr.find(function (e) { return defaultSltFolder == e.name;});
                }

                if((!that.curFolder || !newFolderArr.find(function (e) { return e.name == that.curFolder.name; }))){
                	if(that.curFolder)
                		that.curFolder.select(false);
                    that.curFolder = newFolderArr[0];
                }
                if(that.curFolder)
                    that.curFolder.select(true);
                that.folders = newFolderArr;
                that.statusRefresh();
            });
        },
        createFolder: function(){
            var that = this;
            var folderName = that.dom.confirm.input.val();
            $.getJSON(that.urls.createFolder, {folder: folderName}, function (data) {
                if(data.state != "SUCCESS"){
                    var error = "";
                    if(AJAX_ERR[data.error])
                        error = AJAX_ERR[data.error];
                    alert("创建失败: " + error);
                    return ;
                }
                that.dom.confirm.input.val("");
                that.dom.confirmModal.modal('hide');
                that.loadFolder(folderName);
            });
        },
        selectFolder: function(folder){
            if(this.curFolder != folder)
                this.curFolder.select(false);
            this.curFolder = folder.select(true);
        },
        uploadImage: function () {
            var that = this;
            if(!that.dom.header.uploadImgInput.val())
                return ;
            that.optionHint("正在上传...");
            that.dom.header.uploadImageForm.ajaxSubmit({
                type: 'post',
                url: that.urls.uploadImage + '?category=' + that.curFolder.name + '&size=' + that.curImgSlt.uploadSize,
                success: function(data){
                    that.replaceFileUploadInput();
                    data = data.replace(/<.?[Pp][Rr][Ee]>/g,""); /* ie8中的data字符串中会有<pre>标签包围，转json格式会失败*/
                    var uploadInfo = eval('(' + data + ')');
                    if(uploadInfo.state == "SUCCESS"){
                        that.optionHint("成功上传一张图片。", 2000);
                        that.curFolder.appendImage(uploadInfo.url);
                    }else {
                        that.optionHint("上传失败：" + uploadInfo.message, 2000);
                        alert("上传失败：" + uploadInfo.message);
                    }
                    that.loadFolder();
                },
                error: function(){
                    that.optionHint("");
                    that.replaceFileUploadInput();
                    alert( "连接错误");
                }
            });
        },
        optionHint: function(hint, dismissMillis){
            var that = this;
            hint = hint ? hint : "";
            that.dom.footer.optionHint.html(hint);
            if(dismissMillis){
                setTimeout(function(){
                    that.optionHint("");
                }, dismissMillis);
            }
        },
        replaceFileUploadInput: function () {
            var newInput = $('<input type="file" accept=".jeg,.jpeg,.png,.gif">').change(function () {
                uploadImg(form, progress, $(this).val(), '', uploadUrl);
            });
        },
        selectImage: function(img){
            var that = this;
            if(that.status != IU_STATUS.SELECT)
                return ;
            img.select(!img.selected);

            var sltImgs = that.curSelectImages;
            if(that.curImgSlt.mode == MODE.SINGLE){
                var lastSltImg = sltImgs[0];
                if(lastSltImg && lastSltImg != img && img.selected){
                    sltImgs.splice(0, 1);
                    lastSltImg.select(false);
                    lastSltImg.folder.imgSelect(lastSltImg);
                }
            }
            img.selected ? sltImgs.push(img) : sltImgs.splice(sltImgs.indexOf(img), 1);
            img.folder.imgSelect(img);
            that.statusRefresh();
        },
        selectConfirm: function(){
            this.dom.modal.modal('hide');
            var sltImgs = [];
            $.each(this.curSelectImages, function(i, e){
                sltImgs.push(e.url);
            });
            this.curImgSlt.selectFinish(sltImgs);
            this.curImgSlt = null;
        },
        enterDeleteMode: function(){
            this.status = IU_STATUS.DELETE;
            this.statusRefresh();
        },
        exitDeleteMode: function(){
            this.status = IU_STATUS.SELECT;
            this.statusRefresh();
        },
        statusRefresh: function(){
            var iu = this;
            var iud = iu.dom;
            if(iu.status == IU_STATUS.DELETE){
                iud.footer.enterDeleteModeBtn.hide();
                iud.footer.exitDeleteModeBtn.show();
                iud.body.imgViewPanel.find(".img-delete-btn").fadeIn(200);
                iud.modal.addClass('delete-mode');
                iud.header.uploadImageBtn.addClass('disabled');
                iud.footer.folderCreateBtn.addClass('disabled');
                iud.footer.confirmBtn.addClass('disabled');
            } else {
                iud.footer.enterDeleteModeBtn.show();
                iud.footer.exitDeleteModeBtn.hide();
                iud.body.imgViewPanel.find(".img-delete-btn").hide();
                iud.modal.removeClass('delete-mode');
                iud.header.uploadImageBtn.removeClass('disabled');
                iud.footer.folderCreateBtn.removeClass('disabled');
                iud.footer.confirmBtn.removeClass('disabled');
            }
            if(iu.curImgSlt)
                iud.header.title.text(iu.curImgSlt.mode == MODE.SINGLE ? "选择图片" : "添加图片");
            $.each(this.curSelectImages, function(i, e){
                e.selectNum(i + 1);
            });
            
            $.each(this.folders, function(_, e){
            	e.statusRefresh();
            });
        },
        deleteImage: function(img){
            var that = this;
            if(!window.confirm("确定删除该图片？"))
                return ;
            $.getJSON(that.urls.deleteImage, {folder: that.curFolder.name, image: img.url}, function (data) {
                if (data.state != 'SUCCESS'){
                    console.log('Failed to delete the file. filename: ' + img);
                    alert("删除失败：" + data.msg);
                    return ;
                }
                that.deleteImageFinish(img);
            });
        },
        deleteImageFinish: function(img){
            if(img.selected){
                this.curSelectImages.splice(this.curSelectImages.indexOf(img), 1);
            }
            img.folder.deleteImage(img);
            this.loadFolder();
        },
        init: function () {
            if(this.inited)
                return ;
            this.genDom();
            this.loadFolder();
            this.inited = true;
        },
        genDom: function(){
            var iudom = {header: {}, body: {}, footer: {}, confirm: {}};
            this.dom = iudom;
            var iu = this;
            iudom.modal = $('<div class="modal iu-modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">\
                                    </div>').append(
                iudom.dialog = $('<div class="modal-dialog" style="width:800px;">\
                                        </div>').append(
                    iudom.modalContent = $('<div class="modal-content"></div>')
                )
            );
            iudom.modalContent.append($('<div class="modal-header">\
                            </div>').append(
                $('<div class="col-sm-2 pull-right upload-panel" ></div>').append(
                    iudom.header.uploadImageForm = $('<form action="" class="" style="padding:0px;" method="post"> </form>').append(
                        iudom.header.uploadImageBtn = $('<span class="btn btn-primary btn-sm fileinput-button col-sm-offset-2" multiimg="false"><i class="fa fa-picture-o"></i>\
                            <span>上传图片...</span></span>').append(
                            iudom.header.uploadImgInput = $('<input type="file" name="imgFile" multiple="" accept=".jpg,.jpeg,.png">')
                        )
                    )
                )
            ).append(
                iudom.header.title = $('<h4 class="modal-title" >选择图片</h4>')
            )).append(
                $('<div class="modal-body modal-container">\
                    </div>').append(
                    $('<div class="folder-container"></div>').append(
                        $('<div class="folder-selectable" style="height: 93%;"></div>').append(
                            iudom.body.folderItemPanel = $('<ul class="folder-list"></ul>')
                        )
                    ).append(
                        $('<div class="folder-create"></div>')
                    )
                ).append(
                    iudom.body.imgViewPanel = $('<div class="img-container"></div>')
                )
            ).append(
                $('<div class="modal-footer" style="border: 0;"></div>').append(
                    $('<div class="footer-left-panel pull-left"></div>').append(
                        iudom.footer.folderCreateBtn = $('<button class="btn-sm btn btn-default">新目录</button>')
                    ).append(
                        iudom.footer.enterDeleteModeBtn = $('<button class="btn-sm btn btn-default">进入删除模式</button>')
                    ).append(
                        iudom.footer.exitDeleteModeBtn = $('<button class="btn-sm btn btn-danger">退出删除模式</button>')
                    )
                ).append(
                    iudom.footer.optionHint = $('<span class="iu-option-hint"></span>')
                ).append(
                    iudom.footer.cancelBtn = $('<button class="btn btn-sm btn-default" data-dismiss="modal">关闭</button>')
                ).append(
                    iudom.footer.confirmBtn = $('<button class="btn btn-sm btn-primary">确认</button>')
                )
            );

            iudom.footer.enterDeleteModeBtn.click(function(){
                iu.enterDeleteMode();
            });

            iudom.footer.exitDeleteModeBtn.click(function(){
                iu.exitDeleteMode();
            });

            iudom.confirmModal = $('<div class="modal iu-modal fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false"></div>').append(
                $('<div class="modal-dialog" style="width:700px"></div>').append(
                    $('<div class="modal-content"></div>').append(
                        $('<div class="modal-header">\
                                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>\
                                <h4 class="modal-title" id="modal-title">创建文件夹</h4>\
                           </div>\
                           <div class="modal-body" id="">\
                            <form class="form-horizontal ">\
                                <div class="form-group">\
                                    <label class="col-sm-3 control-label">文件夹名：</label>\
                                <div class="col-sm-8">\
                                    <input type="text" class="form-control" name="folder">\
                                </div>\
                                </div>\
                            </form>\
                           </div>')
                    ).append(
                        $('<div class="modal-footer">').append(
                            $('<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">取消</button>')
                        ).append(
                            iudom.confirm.confirmBtn = $('<button type="button" class="btn btn-sm btn-primary" >创建</button>')
                        )
                    )
                )
            );

            iudom.footer.exitDeleteModeBtn.hide();
            iudom.confirm.input = iudom.confirmModal.find("input");
            $("body").append(iudom.modal).append(iudom.confirmModal);

            iudom.footer.folderCreateBtn.click(function(){
                iudom.confirmModal.modal({
                    keyboard: false,
                    backdrop: false
                });
            });

            iudom.body.imgViewPanel.scroll(function(){
                var cf = iu.curFolder;
                if (!cf || cf.loadStatus != LOAD_STATUS.LOAD_PARTITION)
                    return;
                var $this =$(this);
                if(this.scrollHeight - $this.height() - $this.scrollTop() <= 40)
                    cf.load();
            });
            iudom.header.uploadImgInput.change(function() {
                iu.uploadImage();
            });

            iudom.footer.confirmBtn.click(function(){
                iu.selectConfirm();
            });

            iudom.confirm.confirmBtn.click(function(){
                iu.createFolder();
            });
            return iudom;
        }
    };

    function Folder(folder, iu) {
        this.name = folder.name;
        this.empty = folder.empty;
        this.images = [];
        this.loaded = 0;
        this.selected = false;
        this.imgSelectCount = 0;
        this.dom = this.init();   //{menu} this.needRefresh = false;
        this.loadStatus = LOAD_STATUS.NOT_START;
        this.iu = iu;
    }

    Folder.prototype = {
        init: function(){
            var that = this;
            var folderItem = $('<li class="folder-item">' + this.name +'</li>');
            var emptyHint = $('<span class="empty-folder-hint">该文件夹没有图片<br>点击“上传图片”按钮上传</span>');
            emptyHint.hide();
            var folderImgSelectBadge = $('<span class="badge badge-primary folder-img-select-badge"></span>');
            var deleteBtn = $('<i class="fa fa-times delete-btn"></i>');
            return { folderItem: folderItem.append(folderImgSelectBadge).append(deleteBtn),
            	deleteBtn: deleteBtn, 
            	imgContainer: $('<div style="display: none;"></div>').append(emptyHint),
                emptyHint: emptyHint,
                folderImgSelectBadge: folderImgSelectBadge
            };
        },
        select: function(selected){
            var $fi = this.dom.folderItem;
            var $ic = this.dom.imgContainer;
            if(this.selected = selected){
                $fi.addClass(ON_STATUS.FOLDER_SELECT);
                $ic.show();
                if(this.loadStatus == LOAD_STATUS.NOT_START)
                    this.load();
            } else {
                $fi.removeClass(ON_STATUS.FOLDER_SELECT);
                $ic.hide();
            }
            return this;
        },
        imgSelect: function(img){
            img.selected ? this.imgSelectCount++ : this.imgSelectCount--;
            this.statusRefresh();
        },
        load: function(){
            var that = this;
            that.loadStatus = LOAD_STATUS.LOADING;
            var iu = that.iu;
            $.getJSON(iu.urls.listImage, {start: that.loaded, size: iu.pageSize, category: that.name}, function(data) {
                var loadCount = 0;
                var imgData = [];
                if (data.state == 'SUCCESS' && data.list){
                    loadCount = data.list.length;
                    $.each(data.list, function(i, e){
                        imgData.push(e.url);
                    });
                }
                that.loadStatus = loadCount < iu.pageSize ? LOAD_STATUS.LOAD_FINISH : LOAD_STATUS.LOAD_PARTITION;
                that.appendImage(imgData);
            });
            return that;
        },
        remove: function(){
        	if(!window.confirm("确认删除该图片文件夹？"))
        		return ;
        	var that = this;
        	$.getJSON(that.iu.urls.deleteFolder, {file: that.name}, function(data){
        		if (data.state == 'SUCCESS')
        			that.iu.loadFolder();
                else
                	alert('删除文件夹失败：' + (data.msg || data.error));
        	});
        },
        deleteImage: function(img){
            var data = this.images;
            img.delete();
            if(img.selected)
                this.imgSelectCount--;
            data.splice(data.indexOf(img), 1);
            this.statusRefresh();
            return this;
        },
        appendToPanel: function(){
            var that = this;
            var fi = that.dom.folderItem;
            fi.click(function () {
                that.iu.selectFolder(that);
            });
            that.dom.deleteBtn.click(function(event){
            	that.remove();
            	event.stopPropagation();
            })
            that.iu.dom.body.folderItemPanel.append(fi);
            if(!that.appended){
                that.iu.dom.body.imgViewPanel.append(that.dom.imgContainer);
                that.appended = true;
            }
        },
        appendImage: function(imgUrl){
            var that = this;
            var container = that.dom.imgContainer;
            if($.isArray(imgUrl)){
                $.each(imgUrl, function (inx, e){
                    var image = new Image(e, that);
                    that.images.push(image);
                    container.append(image.dom.item);
                });
            } else {
                var image = new Image(imgUrl, that);
                that.images.unshift(image);
                container.prepend(image.dom.item);
            }
            this.statusRefresh();
            iu.statusRefresh();
            return that;
        },
        statusRefresh: function(){
            var that = this;
            that.loaded = this.images.length;
            that.loaded ? that.dom.emptyHint.hide() : that.dom.emptyHint.show();

            if(that.iu.status == IU_STATUS.DELETE){
            	that.dom.folderImgSelectBadge.hide();
            	if(that.empty)
            		that.dom.deleteBtn.show();
            	return ;
            } else {
            	that.dom.deleteBtn.hide();
            }
            if(that.iu.curImgSlt){
                var badgeStr = that.iu.curImgSlt.mode == MODE.SINGLE ? '<i class="fa fa-check"></i>' : that.imgSelectCount;
                that.imgSelectCount ? that.dom.folderImgSelectBadge.html(badgeStr).show() : that.dom.folderImgSelectBadge.hide();
            }
            return that;
        }
    };

    function Image(url, folder){
        this.url = url;
        this.selected = false;
        this.folder = folder;
        this.iu = folder.iu;
        this.dom = this.init();
    }

    Image.prototype = {
        imgViewHtml: function(){
            return '<div class="img-item" >\
                        <div class="img-item-loader" style="background-image: url(&quot;' + this.url + '&quot;);"></div>\
                        <i class="fa fa-times img-delete-btn"></i>\
                        <span class="selected-icon">\
                            <i class="select-icon-num fa"></i>\
                        </span>\
                    </div>';
        },
        select: function(selected, num){
            var $e = this.dom.item;
            var $n = this.dom.iconNum;
            (this.selected = selected) ? $e.addClass(ON_STATUS.IMG_SELECT) : $e.removeClass(ON_STATUS.IMG_SELECT);

        },
        selectNum: function(num){
            var $n = this.dom.iconNum;
            num == 1 && this.iu.curImgSlt.mode == MODE.SINGLE ? $n.addClass("fa-check").html("") : $n.removeClass("fa-check").html(num);
        },
        delete: function(){
            this.dom.item.remove();
        },
        init: function () {
            var that = this;
            var imgView = $(that.imgViewHtml());

            imgView.click(function () {
                that.iu.selectImage(that);
            }).delegate('i', 'click', function () {
                that.iu.deleteImage(that);
            });
            return {item: imgView, iconNum: imgView.find(".select-icon-num")};
        }
    };

    function ImageSelectItem(url, imgSlt, inx){
        this.url = url;
        this.imageSelect = imgSlt;
        this.index = inx;
        this.dom = this.init();
    }

    ImageSelectItem.prototype = {
        init: function(){
            var that = this;
            var isidom = {
                item: $('<div class="img-item" ></div>'),
                img: $('<div class="img-item-loader" style="background-image: url(&quot;' + this.url + '&quot;);"></div>'),
                deleteBtn: $('<a type="button" class="btn btn-danger btn-xs usi-delete-btn" >删除</a>'),
                leftShiftBtn: $('<i class="isi-shift fa fa-arrow-circle-left" style="left: 8px;"></i>'),
                rightShiftBtn: $('<i class="isi-shift fa fa-arrow-circle-right" style="right: 8px;"></i>')
            };
            isidom.item.append(isidom.img).append(isidom.deleteBtn);
            var total = that.imageSelect.images.length;
            if(that.index > 0 && total > 1)
            	isidom.item.append(isidom.leftShiftBtn);
            
            if(that.index < total - 1 && total > 1)
            	isidom.item.append(isidom.rightShiftBtn);
            	
            isidom.deleteBtn.click(function () {
                that.imageSelect.deleteImage(that);
            });
            
            isidom.leftShiftBtn.click(function(){
            	that.imageSelect.exchange(that, that.index - 1);
            });
            
            isidom.rightShiftBtn.click(function(){
            	that.imageSelect.exchange(that, that.index + 1);
            });
            
            return isidom;
        },
        update: function(url){
        	this.url = url;
        	this.dom.img.css("backgroundImage", 'url(' + url + ')');
        }
    };

    var SI_MODE = {
    	DEFAULT: 0,	//default
    	SILENCE: 1,
    	from: function(t){return from(t, this.DEFAULT, ['silence', this.SILENCE])}
    };
    function ImageSelect(initEle, iu, uOpt){
        uOpt ? '' : (uOpt = {});
        if(!uOpt.images && uOpt.image)
            uOpt.images = [uOpt.image];

        this.mode = MODE.from(uOpt.mode);
        this.siMode = SI_MODE.from(uOpt.siMode);
        
        this.initEle = this.siMode == SI_MODE.SILENCE ? initEle[0]: $(initEle);
        this.data = DATA_TYPE.from(uOpt.data);
        this.images = uOpt.images ? uOpt.images : [];
        this.change = uOpt.change;
        
        this.uploadSize = uOpt.size ? uOpt.size : '';

        this.items = [];
        this.iu = iu;
        this.dom = this.init();

        this.updateSelectItems();
    }
    
    ImageSelect.prototype = {
        deleteImage: function (isi) {
            var that = this;
            that.items.splice(that.items.indexOf(isi), 1);
            that.images = [];
            $.each(that.items, function(i, e){
                that.images.push(e.url);
            });
            that.updateSelectItems();
            if($.isFunction(that.change))
                that.change(null, isi.url);
        },
        init: function(){
            var that = this;
            var isdom = {};
            
            if(SI_MODE.SILENCE == that.siMode){
            	that.initEle.startImgSelect = function(){
            		that.iu.userStart(that);
            	};
            } else {
            	var selectBtnTxt = that.mode == MODE.SINGLE ? "选择图片" : "添加图片";
                isdom = {
                    container: that.initEle.parent(),
                    selectItem: $('<div class="col-sm-12 img-block"></div>'),
                    selectBtn: $('<span class="btn btn-sm btn-primary user-start-btn"><i class="fa fa-picture-o"></i> ' + selectBtnTxt + '...</span>')
                };
            	isdom.container.append(isdom.selectItem).append(isdom.selectBtn);
            	isdom.selectBtn.click(function () {
                    that.iu.userStart(that);
                });
            }
            return isdom;
        },
        exchange: function(isi, shiftInx){
        	if(shiftInx < 0 || shiftInx > this.images.length - 1)
        		return ;
        	var isiImg = this.images[isi.index];
        	var exImg = this.images[isi.index] = this.images[shiftInx];
        	isi.update(exImg);
        	this.items[shiftInx].update(this.images[shiftInx] = isiImg);
        	this.updateInput();
        },
        updateSelectItems: function(){
        	if(this.siMode == SI_MODE.SILENCE)
        		return ;
            var that = this;
            that.dom.selectItem.empty();
            that.items = [];
            $.each(that.images, function(i, e){
                var nisi = new ImageSelectItem(e, that, i);
                that.items.push(nisi);
                that.dom.selectItem.append(nisi.dom.item);
            });
            that.updateInput();
        },
        selectFinish: function(imgUrls){
            var that = this;
            var deleteItems = null;
            var addItems = imgUrls;
            if(!imgUrls.length)
                return ;

            if(that.mode == MODE.SINGLE){
                if(that.images.length){
                    if(that.images[0] == imgUrls[0])
                        return ;
                    deleteItems = that.images;
                }
                that.images = imgUrls;
            } else {
                that.images = that.images.concat(imgUrls);
            }
            that.updateSelectItems();
            if($.isFunction(that.change))
                that.change(addItems, deleteItems);
        },
        val: function(imgs){
            if(typeof(imgs) == "undefined")
                return this.images.join(',');
            else if(!$.isArray(imgs) && imgs)
                imgs = [imgs.split(',')];
            else
                imgs = [];
            this.images = imgs;
            this.updateSelectItems();
            return this;
        },
        updateInput: function(){
            var that = this;
            var vals = [];
            $.each(that.items, function(i, e){
                vals.push(e.url);
            });
            if($.isFunction(that.initEle.val)){
            	if(that.data == DATA_TYPE.JSON)
            		that.initEle.val(JSON.stringify(vals));
            	else
            		that.initEle.val(vals.join(','));
            }
        },
        remove: function(){
        	if(this.siMode == SI_MODE.SILENCE)
        		return ;
            this.dom.selectItem.remove();
            this.dom.selectBtn.remove();
        }
    };
    function imgUpload(uOpt){
        return iu.initSelect(this, uOpt);
    }

    $.fn.extend({
        imgUpload: imgUpload
    });
})(window, document, jQuery);
